package com.wlr.blog.web.common.utils;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/11/29 15:32
 */
@Component
public class ElasticSearchUtils {
    @Autowired
    ElasticsearchClient elasticsearchClient;

    /**
     * 初始化并插入
     *
     * @param index    索引名
     * @param document 数据
     * @return 响应结果
     */
    public <T> String initIndexAndInsert(String index, T document, Long id) throws IOException {
        BooleanResponse exists = elasticsearchClient.indices().exists(i -> i.index(index));
        if (!exists.value()) {
            elasticsearchClient.indices().create(i -> i.index(index));
        }
        IndexResponse indexResponse = elasticsearchClient.index(i -> i
                .index(index)
                .id(String.valueOf(id))
                .document(document));
        return indexResponse.result().jsonValue();
    }

//    public String search(String index,){
//
//    }
}
